// 事件总线 | 发布订阅
class EventEmitter {
    constructor() {
        this.cache = {}
    }

    on(name, fn){
        if(this.cache[name]){
            this.cache[name].push(fn)
        }else{
            this.cache[name] = [fn]
        }
    }

    off(name, fn){
        const tasks = this.cache[name]
        if(tasks){
            const index = tasks.findIndex((f) => f === fn || f.callback === fn)
            if(index >= 0){
                tasks.splice(index, 1)
            }
        }
    }

    emit(name, once = false){
        // 创建副本，如果回调函数内解析注册相同事件，会造成四循环
        const tasks = this.cache[name].slice()
        for(let fn of tasks){
            fn()
        }
        if(once){
            delete this.cache[name]
        }
    }
}

// 测试
const eventEmitter = new EventEmitter()
eventEmitter.on("beforeRun", function(){
    console.log("注册1")
})

eventEmitter.on("beforeRun", function(){
    console.log("注册2")
})

eventEmitter.emit("beforeRun")

